package com.newflypig.jblog.dao.hibernate;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.newflypig.jblog.dao.ITagDAO;
import com.newflypig.jblog.model.Tag;

@Repository("tagDao")
public class TagDaoImpl extends BaseHibernateDAO<Tag> implements ITagDAO{
	
	/**
	 * 从视图中检索全部tag
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Tag> findAll() {
		List<Tag> list = new ArrayList<Tag>();
		String sql = "select tag.id, tag.title, tag.url_name, tag.count from jblog2.jblog_tags_v tag order by tag.count desc";
		List<Object[]> objectList = this.getSession().createSQLQuery(sql).list();
		for(int i = 0 ; i < objectList.size(); i++){
			Tag tag = new Tag();
			tag.setTagId((Integer) objectList.get(i)[0]);
			tag.setTitle((String) objectList.get(i)[1] );
			tag.setUrlName((String) objectList.get(i)[2] );
			tag.setCount(((BigInteger) ( objectList.get(i)[3] )).longValue());
			
			list.add(tag);
		}
		return list;
	}

	@Override
	public void makeConnect(Integer tagId, Integer articleId) {
		String sql = "insert into jblog2.jblog_article_tags(jblog_article_id,jblog_tags_id) values(:articleId,:tagId)";
		this.getSession()
			.createSQLQuery(sql)
			.setInteger("articleId", articleId)
			.setInteger("tagId", tagId)
			.executeUpdate();
	}

	@Override
	public void cleanConnect(Integer articleId) {
		String sql = "delete from jblog2.jblog_article_tags where jblog_article_id = :articleId";
		this.getSession()
			.createSQLQuery(sql)
			.setInteger("articleId", articleId)
			.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> findAllFromTable() {
		String sql = "select tag.title from jblog2.jblog_tags_t tag";
		
		List<String> list = this.getSession().createSQLQuery(sql).list();
		
		return list;
	}

}
